<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="商品分类" prop="categoryId">
        <CategoryCascader v-model="formData.categoryId" />
      </el-form-item>
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入商品标题" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="商品主图" prop="topImage">
        <ImageUpload v-model="formData.topImage" limit="1" />
      </el-form-item>
      <el-form-item label="商品图片" prop="images">
        <ImageUpload v-model="formData.images" limit="10" />
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input-number v-model="formData.price" :min="1" :max="99999999999" type="number" />
      </el-form-item>
      <el-form-item label="是否展示" prop="showFlag">
        <el-switch v-model="formData.showFlag" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="formData.remark"
          placeholder="请输入商品描述"
          type="textarea"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, watch } from "vue";
import { useDictStore } from "@/store/modules/dict";
import { addEditDecorationCategory } from "@/api/article";
import CategoryCascader from "@/components/CategoryCascader/index.vue";
import GoodAPI from "@/api/good";
import ImageUpload from "@/components/ImageUpload/index.vue";
const props = defineProps({
  title: {
    type: String,
    default: "新增商品",
  },
  defaultData: {
    type: Object,
    default: () => null,
  },
  dialogShow: {
    type: Boolean,
    required: true,
    default: false,
  },
});
const dictStore = useDictStore();
const categories = computed(() => dictStore.getDictionary("goodsCategory"));
const dialogVisible = ref(false);
const formData = ref({
  categoryId: null,
  title: "",
  topImage: "",
  images: [],
  price: "",
  showFlag: 1,
  remark: "",
});

const rules = {
  categoryId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
  title: [{ required: true, message: "请输入商品标题", trigger: "blur" }],
  topImage: [{ required: true, message: "请上传商品主图", trigger: "change" }],
  images: [{ required: true, message: "请上传商品图片", trigger: "change" }],
  price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
  showFlag: [{ required: true, message: "请选择是否展示", trigger: "change" }],
};

const formRef = ref(null);
const emit = defineEmits(["update:dialogShow", "initList", "editGood"]);

const handleClose = () => {
  dialogVisible.value = false;
  emit("update:dialogShow", false);
  // 关闭时重置表单
  formData.value = {
    categoryId: null,
    topImage: "",
    images: [],
    price: "",
    showFlag: 1,
    remark: "",
  };
};
const submitForm = () => {
  formRef.value.validate((valid) => {
    let categoryId;
    if (Array.isArray(formData.value.categoryId)) {
      categoryId = formData.value.categoryId[formData.value.categoryId.length - 1];
    } else {
      categoryId = formData.value.categoryId;
    }
    if (valid) {
      let params = {
        ...formData.value,
        topImage: JSON.stringify(formData.value.topImage),
        images: JSON.stringify(
          formData.value.images.map((item) => {
            return { name: item.name, url: item.url };
          })
        ),
        categoryId: categoryId,
      };
      if (props.defaultData) {
        emit("editGood", params);
      } else {
        addGood(params);
      }
      // ElMessage.success("提交成功");
      // 提交表单数据...
    } else {
      //ElMessage.error("请检查表单");
      return false;
    }
  });
};
const addGood = async (params) => {
  try {
    const data = await GoodAPI.addGood(params);
    emit("initList");
    handleClose();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
};
const resetForm = () => {
  formRef.value.resetFields();
};

const handlePictureCardPreview = (file) => {
  console.log(file);
};

const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};
// 监听对话框显示状态
watch(
  () => props.dialogShow,
  (newVal) => {
    dialogVisible.value = newVal;
    console.log(!props.defaultData);
    if (!props.defaultData) {
      formData.value = {
        categoryId: null,
        topImage: "",
        images: [],
        price: "",
        showFlag: 1,
        remark: "",
      };
    } else {
      formData.value = {
        ...props.defaultData,
        topImage: JSON.parse(props.defaultData.topImage),
        images: JSON.parse(props.defaultData.images),
        //categoryId: formData.value.categoryId.split(","),
      };
    }
  }
);
const cancel = () => {
  handleClose();
};
onMounted(() => {});
</script>
